package cn.cvs.controller;

import cn.cvs.pojo.SysRole;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.sysRole.SysRoleService;
import cn.cvs.service.user.SysUserService;
import cn.cvs.utils.Constants;
import cn.cvs.utils.PageSupport;
import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/sys/user/")
public class SysUserController {
    private static final Logger logger = Logger.getLogger(SysUserController.class);
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysRoleService sysRoleService;

    @RequestMapping("/list")
    public String list(@RequestParam(value = "pageIndex",required = false)String pageIndex,
                       @RequestParam(value = "queryRealName",required = false)String queryRealName,
                       @RequestParam(value = "queryRoleId",required = false) Integer queryRoleId,
                       Model model, HttpSession session) throws Exception {
        logger.info("queryRealName:"+queryRealName);
        logger.info("queryRoleId:"+queryRoleId);
        //默认页码
        Integer currentPageNo=1;
        //每页显示的记录数
        Integer pageSize = Constants.pageSize;

        //从请求的参数中获取pageIndex，并转换为当前页码
        if (pageIndex!=null&&!"".equals(pageIndex)){
            currentPageNo=Integer.valueOf(pageIndex);
        }
        //获取总记录数
        Integer totalCount = sysUserService.findUserTotalCount(queryRealName,queryRoleId);
        //计算总页数
        PageSupport pageSupport =new PageSupport();
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);
        //总页数
        Integer totalPageCount = pageSupport.getTotalPageCount();
        //控制页码
        if (currentPageNo<1){
            currentPageNo=1;
        }else if (currentPageNo>totalPageCount){
            currentPageNo=totalPageCount;
        }
        //获取业务层中的用户列表
        List<SysUser> userlist = sysUserService.findUserByPage(currentPageNo,pageSize,queryRealName,queryRoleId);
        List<SysRole> roleList = sysRoleService.findAllSysRole();
        SysUser sysUser = (SysUser) session.getAttribute("userSession");
        model.addAttribute("userList",userlist);
        model.addAttribute("roleList",roleList);
        model.addAttribute("totalCount",totalCount);
        model.addAttribute("currentPageNo",currentPageNo);
        model.addAttribute("totalPageCount",totalPageCount);
        model.addAttribute("queryRealName",queryRealName);
        model.addAttribute("queryRoleId",queryRoleId);
        model.addAttribute("sysuserid",sysUser.getId());
        //逻辑视图名
        return "sysUser/list";
    }

    @RequestMapping("/toAdd")
    public String toAdd(){
        return "sysUser/add";
    }

    @PostMapping("/add")
    public String add(SysUser sysUser, HttpServletRequest request, HttpSession session,
                      @RequestParam(value = "attachs",required = false) MultipartFile[] attachs) throws Exception {
        System.out.println("新增方法");
        String idPicPath = null;
        String workPicPath = null;
        String errorInfo = null;
        boolean flag = true;
        String path = session.getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
        System.out.println("路径名:"+path);
        for (int i = 0;i < attachs.length;i++){
            MultipartFile attach = attachs[i];
            if (!attach.isEmpty()){
                if (i == 0){
                    errorInfo = "updateFileError";
                }else if (i == 1){
                    errorInfo = "updateWpError";
                }
                String odlFileName = attach.getOriginalFilename();
                System.out.println("原文件名:"+odlFileName);
                String prefix = FilenameUtils.getExtension(odlFileName);
                System.out.println("后缀名:"+prefix);
                int fileSize = 1500000;
                System.out.println("上传文件大小:"+fileSize);
                if (attach.getSize()>fileSize){
                    request.setAttribute(errorInfo,"*上传文件不得大于1500000");
                    flag = false;
                }else if (prefix.equalsIgnoreCase("jpg")
                        ||prefix.equalsIgnoreCase("png")
                        ||prefix.equalsIgnoreCase("jpeg")
                        ||prefix.equalsIgnoreCase("pneg")){//上传图片格式不正确
                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1500000)+"_Personal."+prefix;
                    System.out.println("新文件名:"+fileName);
                    File targetFile = new File(path);
                    if (!targetFile.exists()){
                        targetFile.mkdirs();
                    }
                    //保存
                    try {
                        attach.transferTo(new File(targetFile,fileName));
                    }catch (Exception e){
                        e.printStackTrace();
                        request.setAttribute(errorInfo,"*上传文件失败");
                        flag = false;
                    }
                    if (i == 0){
                        idPicPath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator+fileName;
                    }else if (i == 1){
                        workPicPath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator+fileName;
                    }
                    System.out.println(idPicPath);
                    System.out.println(workPicPath);
                }else {
                    request.setAttribute(errorInfo,"*上传图片格式不正确");
                    flag = false;
                }
            }
        }
        if (flag) {
            logger.info("进入添加用户方法，参数：" + sysUser);
            sysUser.setCreatedUserId(((SysUser) session.getAttribute(Constants.USER_SESSION)).getId());
            sysUser.setCreatedTime(new Date());
            sysUser.setIdPicPath(idPicPath);
            sysUser.setWorkPicPath(workPicPath);
            if (sysUserService.saveSysUser(sysUser)) {
                return "redirect:/sys/user/list";
            }
        }
        return "sysUser/add";
    }

    @RequestMapping("/toUpdate")
    public String toUpdate(Model model, @RequestParam String uid) throws Exception {
        //通过Id获取对象
        SysUser sysUser = sysUserService.findUserById(uid);
        //添加模型数据
        model.addAttribute("sysUser",sysUser);
        return "sysUser/update";
    }

    @RequestMapping(value = "/update")
    public String update(SysUser sysUser, HttpServletRequest request, HttpSession session,
                         @RequestParam(value = "attachs",required = false) MultipartFile[] attachs) throws Exception {
        System.out.println("新增方法");
        String idPicPath = null;
        String workPicPath = null;
        String errorInfo = null;
        boolean flag = true;
        String path = session.getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
        logger.info("文件存储路径：" + path);
        for (int i = 0; i < attachs.length; i++) {
            MultipartFile attach = attachs[i];
            if (!attach.isEmpty()) {
                if (i == 0) {
                    errorInfo = "uploadFileError";
                } else if (i == 1) {
                    errorInfo = "uploadWpError";
                }
                String oldFileName = attach.getOriginalFilename();//原文件名
                logger.info("原文件名：" + oldFileName);//原文件后缀
                String prefix = FilenameUtils.getExtension(oldFileName);
                logger.info("原文件名后缀：" + prefix);
                int filesize = 150000000;
                logger.info("上传文件大小：" + attach.getSize());
                if (attach.getSize() > filesize) {//上传大小不得超过500KB
                    request.setAttribute(errorInfo, " * 上传大小不得超过1500000KB");
                    flag = false;
                } else if (prefix.equalsIgnoreCase("jpg")
                        || prefix.equalsIgnoreCase("png")
                        || prefix.equalsIgnoreCase("jpeg")
                        || prefix.equalsIgnoreCase("pneg")) {//上传图片格式不正确
                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(150000000) + "_Personal." + prefix;
                    logger.info("新文件名称：" + fileName);
                    File targetFile = new File(path);
                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                    }
                    //保存
                    try {
                        attach.transferTo(new File(targetFile, fileName));
                    } catch (Exception e) {
                        e.printStackTrace();
                        request.setAttribute(errorInfo, " * 上传失败！");
                        flag = false;
                    }
                    if (i == 0) {
                        idPicPath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
                    } else if (i == 1) {
                        workPicPath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
                    }
                    logger.info("idPicPath："+idPicPath);
                    logger.info("workPicPath："+workPicPath);
                }else {
                    request.setAttribute(errorInfo," * 上传图片格式不正确");
                    flag = false;
                }
            }
        }
        if (flag) {
            logger.info("进入修改用户方法，参数：" + sysUser);
            //设置证件照的图片路径
            sysUser.setIdPicPath(idPicPath);
            sysUser.setWorkPicPath(workPicPath);
            //设置创建者的编号（使用Session从登录用户中获取）
            SysUser userSession = (SysUser) session.getAttribute("userSession");
            sysUser.setCreatedUserId(userSession.getId());

            if (sysUserService.updateUser(sysUser)) {
                return "redirect:/sys/user/list";
            }
        }
        return "sysUser/update";
    }


    @RequestMapping(value = "/view/{id}",method = RequestMethod.GET)
    public String toView(@PathVariable String id,Model model)throws Exception{
        SysUser sysUser = sysUserService.findUserById(id);
        model.addAttribute("sysUser",sysUser);
        return "sysUser/view";

    }

    /**
     * 退出系统
     * @param session
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute(Constants.USER_SESSION);
        logger.info("退出系统，清除session用户集合数据");
        return "login";
    }

    /**
     * Ajax删除用户信息
     * @param uid
     */
    @ResponseBody
    @DeleteMapping("/del/{uid}")
    public Object del(@PathVariable String uid) throws Exception {
        logger.info("进入删除用户信息方法，参数"+uid);
        HashMap<String,Object> resultMap = new HashMap<String, Object>();
        SysUser sysUser = sysUserService.findUserById(uid);
        if (sysUser == null){//判断该用户是否存在
            resultMap.put("delResult","notexist");
        }else {
            if (sysUserService.delUserById(uid)){//判断是否删除成功
                resultMap.put("delResult","true");
            }else {
                resultMap.put("delResult","false");
            }
        }
        return JSON.toJSONString(resultMap);
    }

    /**
     * Ajax原密码验证
     * @param oldPassword
     * @param session
     * @return
     */
    @ResponseBody
    @PostMapping("/checkOldPwd")
    public Object checkOldPwd(@RequestParam String oldPassword,HttpSession session){
        SysUser sysUser = (SysUser) session.getAttribute(Constants.USER_SESSION);
        HashMap<String,Object> resultMap = new HashMap<String, Object>();
        logger.info("进入原密码验证，原密码"+sysUser.getPassword()+",输入的原密码"+oldPassword);
        if (sysUser == null){//当前用户session过期，请重新登录
            resultMap.put("result","sessionerror");
        }else if (oldPassword == null || oldPassword == ""){//请输入旧密码
            resultMap.put("result","error");
        }else if (oldPassword == sysUser.getPassword() || oldPassword.equals(sysUser.getPassword())){//旧密码正确
            resultMap.put("result","true");
        }else {//原密码输入不正确
            resultMap.put("result","false");
        }
        return JSON.toJSONString(resultMap);
    }


    @RequestMapping("/toUpdatePwd")
    public String toUpdatePwd(Model model){
        SysUser sysUser = new SysUser();
        model.addAttribute("id",sysUser.getId());
        return "sysUser/updatePassword";
    }

    @PostMapping("/savePassword")
    public String savePassword(@RequestParam String newPassword,HttpSession session) throws Exception {
        SysUser sysUser = (SysUser) session.getAttribute(Constants.USER_SESSION);
        logger.info("进入修改密码方法，用户编号：" + sysUser.getId() + ",旧密码：" + sysUser.getPassword() + ",新密码：" + newPassword);
        if (sysUserService.updatePWD(String.valueOf(sysUser.getId()), newPassword)) {
            sysUser.setPassword(newPassword);
            session.removeAttribute(Constants.USER_SESSION);//清除原有用户集合数据
            session.setAttribute(Constants.USER_SESSION, sysUser);//插入新用户集合数据
            logger.info("用户集合的新密码：" + ((SysUser) session.getAttribute(Constants.USER_SESSION)).getPassword());
            return "redirect:/toLogin";//修改密码成功，重定向至user/toMain接口
        }
        return "sysUser/updatePassword";
    }


}
